package de.karnik.dokobu.controllers;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.apache.log4j.Logger;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import de.karnik.dokobu.navigation.NavGenerator;
import de.karnik.dokobu.navigation.NavGroup;
import de.karnik.dokobu.persistence.DoKoBuUser;

public class BaseController {
	
	private static final Logger logger = Logger.getLogger( IngredientsController.class.getName() );
	
	private HashMap<String,Object> baseAttributes;
	private DoKoBuUser currentUser;
	
	public BaseController() {
		this.baseAttributes = new HashMap<String,Object>();
		this.getBaseAttributes().put( "applicationName", "DoKoBu" );
		this.setCurrentDates();
	}
	
	public void init() {
		this.analyzeUserStatus();
		this.generateMenu();
	}
	
	private void analyzeUserStatus() {
		
		UserService userService = UserServiceFactory.getUserService();
		
		if( userService != null &&  !userService.isUserLoggedIn() )
			return;
		
		this.getBaseAttributes().put( "userEmail", 					userService.getCurrentUser().getEmail() );
		this.getBaseAttributes().put( "userNickname", 				userService.getCurrentUser().getNickname() );
		this.getBaseAttributes().put( "userId", 					userService.getCurrentUser().getUserId() );

		
	}
	
	private void setCurrentDates() {
		Date currentDate = new Date();
		SimpleDateFormat year = new SimpleDateFormat( "yyyy" );
		SimpleDateFormat date = new SimpleDateFormat( "EEE, dd. MMM yyyy" );
		
		this.getBaseAttributes().put( "currentYear", year.format( currentDate ) );
		this.getBaseAttributes().put( "currentDate", date.format( currentDate ) );
	}
	
	private void generateMenu() {
		NavGroup menu = new NavGenerator().generateNav( currentUser );
		this.getBaseAttributes().put( "mainNav", menu.getNavElements() );
	}
	
	public HashMap<String,Object> getBaseAttributes() {
		return this.baseAttributes;
	}

	public static Logger getLogger() {
		return logger;
	}
	
	
}
